import React from "react";
import {connect} from "react-redux";
import {fetchPosts, reset} from "../../actions";
import ServiceMenu from "../../components/ServiceMenu";
import TradingRecord from "../../components/TradingRecord";
import cookie from "react-cookie";
import Events from "../../utils/Events";
import isEqual from "lodash/isEqual";
const PAGE_SIZE = 20;
class merchantService extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            pageindex: 1,
            isLoading: true,
            isNoData: false,
            shopInfoList: [],
            shopOrderInfo: [],
            shopNo: 0,
            isMultiShop: false,
            totalIncome: 0,
            totalTreadCount: 0,
            isLoadingMore: false,
            isCanLoadMore: true,
            title: "",
            isExistUser: true
        }
    }

    componentWillMount() {
        document.title = "商家服务";
    }

    componentDidMount() {
        const query = this.props.location.query;
        if (query.openId) {
            cookie.save("openId", query.openId);
        }
        this.setState({
            pageindex: 1
        });
        this.getShopOrderList("");
        this._scrollListener = Events.on(window, 'scroll', this.checkButtom.bind(this));
    }

    componentWillUnmount() {
        //Events.off(window, 'scroll', this.checkButtom.bind(this));
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.OrderList.errorCode === 0 && this.state.pageindex == 1) {
            this.setState({
                isLoading: false
            });
            let orderList = nextProps.OrderList;
            let shopInfoList = orderList.data.shopInfoForStaffVos;
            let shopOrderInfo = orderList.data.shopOrderForEache;
            let totalIncome = orderList.data.totalIncome;
            let totalTreadCount = orderList.data.totalTreadCount;
            if (shopInfoList.length == 1 && totalTreadCount == 0) {
                this.setState({
                    isNoData: true
                });
            }
            if (shopInfoList.length > 0) {
                this.setState({
                    shopInfoList: shopInfoList,
                    isMultiShop: shopInfoList.length > 1,
                    title: orderList.data.title
                });
            }
            let orderLength = 0;
            if (shopOrderInfo.orderVos) {
                orderLength = shopOrderInfo.orderVos.length;
            }
            this.setState({
                shopOrderInfo: shopOrderInfo,
                totalIncome: totalIncome,
                totalTreadCount: totalTreadCount,
                isLoadMore: orderLength > 0
            });
        } else if (nextProps.OrderList.errorCode === 4002) {//用户不存在
            this.setState({
                isLoading: false,
                isExistUser: false
            });
        }

        if (nextProps.OrderList.errorCode === 0 &&
            !isEqual(nextProps.OrderList, this.props.OrderList) && this.state.pageindex > 1) {
            let shopOrderList = nextProps.OrderList.data.shopOrderForEache.orderVos;
            this.setState({
                isLoadingMore: false,
                isCanLoadMore: shopOrderList.length == PAGE_SIZE
            });
            let shopOrderInfo = this.state.shopOrderInfo;
            if (shopOrderList.length > 0) {
                shopOrderList.map((item, index) => {
                    shopOrderInfo.orderVos.push(item);
                });
                this.setState({
                    shopOrderInfo: shopOrderInfo
                })
            }
        }
    }

    render() {
        if (this.state.isLoading) {
            return (<div className="loading"><span>Loading</span></div>);
        } else if (this.state.isNoData) {
            return (
                <div>
                    <div className="merchant-service-title">
                        <label>{this.state.title}</label>
                    </div>
                    <div className="merchant-service-header">
                        <div>
                            <div>0.00</div>
                            <div>今日收入(元)</div>
                        </div>
                    </div>
                    <div className="merchant-service-wait-receipt">等待收款</div>
                    <ServiceMenu selectedIndex="1"/>
                </div>);
        } else if (!this.state.isExistUser) {
            return (
                <div className="horizontal-center">您暂时未有此页面访问权限！</div>
            );
        } else if (this.state.shopOrderInfo.orderVos) {
            return (
                <div>
                    <div className="merchant-service-title">
                        <label>{this.state.title}</label>
                    </div>
                    <div className="merchant-service-header">
                        <div>
                            <div>{this.state.totalIncome}</div>
                            <div>今日收入(元)</div>
                        </div>
                    </div>
                    <TradingRecord shoppingNames={this.state.shopInfoList}
                                   tradingRecords={this.state.shopOrderInfo}
                                   shopNo={this.state.shopNo}
                                   isMultiShop={this.state.isMultiShop}
                                   totalTreadCount={this.state.totalTreadCount}
                                   fetchTradingRecordsByShopId={this.fetchTradingRecordsByShopId.bind(this)}
                    />
                    <ServiceMenu selectedIndex="1"/>
                </div>
            );
        } else {
            return (<div className="horizontal-center">数据有问题,该用户关联店铺数量为：{this.state.shopInfoList.length}！</div>);
        }
    }

    fetchTradingRecordsByShopId() {
        let shopNo = cookie.load("shopNo");
        this.setState({
            shopNo: shopNo,
            pageindex: 1,
            isCanLoadMore: true
        });
        this.getShopOrderList(shopNo);
    }

    getShopOrderList(shopNo) {
        const header = {"X-Client-ID": "123456"};
        this.props.dispatch(reset("getShopOrderList"));
        this.props.dispatch(fetchPosts("getShopOrderList", header, {
            "openId": cookie.load("openId"),
            "shopNo": shopNo,
            "pageindex": 1,
            "pagesize": PAGE_SIZE
        }));
    }

    checkButtom() {
        const header = {"X-Client-ID": "123456"};
        let scrollTop = document.body.scrollTop,
            innerHeight = window.innerHeight,
            scrollHeight = document.body.scrollHeight,
            pageindex = this.state.pageindex;
        if (scrollTop + innerHeight >= scrollHeight && !this.state.isLoadingMore &&
            this.state.isCanLoadMore) {
            this.setState({
                isLoadingMore: true
            });
            pageindex++;
            this.setState({pageindex: pageindex});
            this.props.dispatch(fetchPosts("getShopOrderList", header,
                {
                    "openId": cookie.load("openId"),
                    "shopNo": (this.state.shopNo == 0 ? "" : this.state.shopNo),
                    "pageindex": this.state.pageindex,
                    "pagesize": PAGE_SIZE
                })
            )
        }
    }
}

function mapStateToProps(state) {
    const {postsByApi} = state;
    const {
        isFetching,
        items: OrderList
    } = postsByApi["getShopOrderList"] || {
        isFetching: false,
        items: {}
    };

    return {
        OrderList,
        isFetching
    }
}

export default connect(mapStateToProps)(merchantService);
